import type confetti from 'canvas-confetti'

export type GiftEffectPreset = 'burst' | 'fireworks' | 'side' | 'pride'

export function useGiftEffects() {
  let _confetti: typeof confetti | null = null

  async function ensure() {
    if (!_confetti) {
      const mod = await import('canvas-confetti')
      _confetti = mod.default
    }
    return _confetti!
  }

  async function burst() {
    const c = await ensure()
    c({ particleCount: 100, spread: 70, origin: { y: 0.7 }, zIndex: 9999 })
  }

  async function fireworks(durationMs = 1200) {
    const c = await ensure()
    const end = Date.now() + durationMs
    ;(function frame() {
      c({ particleCount: 6, angle: 60, spread: 55, origin: { x: 0 }, zIndex: 9999 })
      c({ particleCount: 6, angle: 120, spread: 55, origin: { x: 1 }, zIndex: 9999 })
      if (Date.now() < end) requestAnimationFrame(frame)
    })()
  }

  async function side(quantity = 3) {
    const c = await ensure()
    for (let i = 0; i < quantity; i++) {
      setTimeout(() => {
        c({ particleCount: 40, angle: 60, spread: 45, origin: { x: 0 }, zIndex: 9999 })
        c({ particleCount: 40, angle: 120, spread: 45, origin: { x: 1 }, zIndex: 9999 })
      }, i * 200)
    }
  }

  async function pride() {
    const c = await ensure()
    const colors = ['#bb0000', '#ffffff']
    colors.forEach((color, i) => {
      setTimeout(() => {
        c({ particleCount: 80, spread: 60, origin: { y: 0.7 }, zIndex: 9999, colors: [color] })
      }, i * 150)
    })
  }

  async function trigger(preset: GiftEffectPreset | string | undefined, qty?: number) {
    const name = (preset as GiftEffectPreset) || 'burst'
    switch (name) {
      case 'fireworks':
        return fireworks()
      case 'side':
        return side(Math.min(Math.max(qty || 3, 1), 10))
      case 'pride':
        return pride()
      case 'burst':
      default:
        return burst()
    }
  }

  return { trigger }
}
